<template>
  <div>
    <el-dialog :visible.sync="dialogFormVisible">
      <!-- 门店名称 -->
      <el-form ref="subform1" :model="form" :rules="rules">
        <!-- 名称 -->
        <el-form-item label="医院名称：" :label-width="formLabelWidth" prop="hospitalName">
          <el-input v-model="form.hospitalName" class="form" type="text" placeholder="请输入医院名称" />
        </el-form-item>

        <!-- 省份 -->
        <el-form-item label="省份：" :label-width="formLabelWidth" prop="province_id">
          <el-select v-model="form.province_id" class="form" placeholder="请选择省份">
            <el-option
              v-for="item in form.province"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 医院图标 -->
        <el-form-item label="医院图标：" :label-width="formLabelWidth" prop="hospitalIcon">
          <el-upload
            action="https://mpingweb.yuepinyuemei.com/api/upload"
            :data="{
              dirPath: 'authentication',
              upload_status: true }"
            :multiple="false"
            :limit="1"
            list-type="picture-card"
            :on-remove="handleRemove"
            :on-success="upload_main"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog>
            <img width="100%" :src="common.img_url+img_main" alt />
          </el-dialog>
          <img width="20%" :src="common.img_url+form.hospitalIcon" alt />
        </el-form-item>

        <!-- 地址 -->
        <el-form-item label="医院地址：" :label-width="formLabelWidth" prop="locationDes">
          <el-input v-model="form.locationDes" class="form" type="text" placeholder="请输入医院地址" />
        </el-form-item>
        <!-- 医院坐标 -->
        <el-form-item label="医院坐标：" :label-width="formLabelWidth" />
        <!-- 经度 -->
        <el-form-item label="经度：" :label-width="formLabelWidth" prop="locationLng">
          <el-input v-model="form.locationLng" class="form" type="text" placeholder="请输入经度" />
        </el-form-item>
        <!-- 纬度 -->
        <el-form-item label="纬度：" :label-width="formLabelWidth" prop="locationLat">
          <el-input v-model="form.locationLat" class="form" type="text" placeholder="请输入纬度" />
        </el-form-item>
        <!-- 轮播图/展示图 -->
        <el-form-item label="展示图：" :label-width="formLabelWidth" prop="showImage">
          <el-upload
            action="https://mpingweb.yuepinyuemei.com/api/upload"
            :data="{
              dirPath: 'authentication',
              upload_status: true }"
            :multiple="true"
            :limit="9"
            :file-list="img_list"
            :show-file-list="false"
            list-type="picture-card"
            :on-success="upload_arr"
            :before-upload="before_main"
            :on-remove="del_arr"
          >
            <i class="el-icon-plus icon" />
          </el-upload>
          <ul class="img-list">
            <li v-for="(item, index) in img_list" :key="index" class="img-item">
              <img v-if="item.url" :src="item.url" alt class="img" />
              <div class="del-btn" @click.stop="del_arr(item)">
                <i class="el-icon-delete" />
              </div>
            </li>
          </ul>
        </el-form-item>

        <el-form-item label="医院简介：" :label-width="formLabelWidth" prop="hospitalIntro">
          <div class="form">
            <textarea
              id="form-control"
              v-model="form.hospitalIntro"
              type="text"
              class="form-control comment-input"
              placeholder="请输入医院简介，最多输入400字"
              maxlength="400"
              @keyup="selfAdaption($event)"
            />
            <span v-html="form.hospitalIntro.length" />/400字
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain @click="closeMask">取 消</el-button>
        <el-button
          v-if="!isDisabled&&info&&!info.id"
          type="primary"
          plain
          @click="submitInfo('subform1')"
        >确 定</el-button>
        <el-button v-if="!isDisabled&&info&&info.id" type="primary" plain @click="resetInfo">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import { createCategory } from '@/api/category'
import { provinceList } from "../../api/province";
import { addHospital, updateHospital } from "../../api/hospitalAdd";
import { updateArticle } from "../../api/article";
import { validLonreg } from "../../utils/validate";

export default {
  props: {
    isHidden: {
      type: Boolean,
      default: false,
    },
    detailInfo: {
      id: "",
    },
    isDisabled: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      formLabelWidth: "120px", // 列表label宽度
      infos: this.detailInfo, // 传过来的信息
      form: {
        hospitalName: "", // 医院名称
        province: [], // 省份列表
        province_id: "", // 省份id
        locationDes: "", // 医院地址
        hospitalIcon: "", // 医院图标
        locationLng: "", // 纬度
        locationLat: "", // 经度
        showImage: "", // 展示图
        hospitalIntro: "", // 医院简介
      },
      img_main: "", // 图片
      img_list: [], // 展示图
      img_arr: [], //   展示图
      info: this.detailInfo,
      dialogFormVisible: this.isHidden, // 是否显示弹出框
      rules: {
        hospitalName: [
          {
            required: true,
            message: "请输入医院名称",
            trigger: "blur",
          },
          {
            max: 19,
            min: 2,
            message: "长度必须在2-19个字符之间",
            trigger: "blur",
          },
        ],
        province_id: [
          {
            required: true,
            message: "请选择省份",
            trigger: "blur",
          },
        ],
        locationDes: [
          {
            required: true,
            message: "请输入医院地址",
            trigger: "blur",
          },
          {
            max: 50,
            min: 5,
            message: "长度必须在5-50个字符之间",
            trigger: "blur",
          },
        ],
        locationLng: [
          {
            required: true,
            message: "请输入经度",
          },
          {
            validator: validLonreg,
            trigger: "blur",
            message: "请输入正确经度",
          },
        ],
        locationLat: [
          {
            required: true,
            message: "请输入纬度",
            trigger: "blur",
          },
          {
            validator: validLonreg,
            trigger: "blur",
            message: "请输入正确纬度",
          },
        ],
        hospitalIntro: [
          {
            required: true,
            message: "请输入医院简介，最多输入400字",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    dialogFormVisible() {
      this.$emit("checkMask", this.dialogFormVisible);
    },
    // 展示图
    img_arr(val) {
      const arr = [];
      if (Array.isArray(val)) {
        val.forEach((item, index) => {
          arr.push({
            name: index,
            url: this.common.img_url + item,
          });
        });
        this.img_list = arr;
        this.$forceUpdate();
      }
    },
  },
  // 自动调用省份接口获取省份
  mounted() {
    this.getProvince();

    // 说明是查看或者编辑 而不是添加
    if (this.infos && this.infos.id) {
      this.form.hospitalName = this.infos.hospitalName;
      this.form.province_id = this.infos.provinceId;
      this.form.locationDes = this.infos.locationDes;
      this.form.locationLng = this.infos.locationLng;
      this.form.locationLat = this.infos.locationLat;
      this.form.hospitalIntro = this.infos.hospitalIntro;
      this.form.hospitalIcon = this.infos.hospitalIcon;
      this.img_arr = this.infos.showImage;
    }
  },
  methods: {
    //
    selfAdaption(e) {
      if (e.target.scrollHeight > 114) {
        return false; // 114是输入框6行的高度，超过6行就使用滚动条
      }
      e.target.style.height = "auto";
      e.target.scrollTop = 0; // 防抖动
      e.target.style.height = e.target.scrollHeight + "px"; // 将输入框高度置为其可滚动高度
    },

    // 图片移除
    handleRemove() {
      this.img_main = "";
    },
    // 图片上传
    upload_main(res) {
      this.img_main = res.data;
    },

    // 上传展示图之前钩子
    before_main() {
      this.loading = true;
    },

    // 上传展示图
    upload_arr(res) {
      this.loading = false;
      const arr = [...this.img_arr];
      arr.push(res.data);
      this.img_arr = arr;
    },
    // 删除展示图
    del_arr(val) {
      const del_url = val.url.split(this.common.img_url)[1];
      this.img_arr.forEach((item, index) => {
        if (del_url === item) {
          this.img_arr.splice(index, 1);
        }
      });
    },

    // 获取省份
    getProvince() {
      provinceList({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then((res) => {
        this.total = res.data.data.count;
        this.pageNum = res.data.data.pageNum;
        this.pageSize = res.data.data.pageSize;
        this.form.province = res.data.data.list;
      });
    },

    closeMask() {
      this.$refs["subform1"].resetFields();
      this.dialogFormVisible = false;
      this.$emit("checkMask", this.dialogFormVisible);
    },
    // 添加
    submitInfo() {
      if (this.checkInfo()) {
        // 提交表单 隐藏弹窗
        addHospital({
          hospitalName: this.form.hospitalName,
          province: this.form.province_id + "",
          locationDes: this.form.locationDes,
          hospitalIcon: this.img_main,
          locationLng: this.form.locationLng,
          locationLat: this.form.locationLat,
          showImage: this.img_arr,
          hospitalIntro: this.form.hospitalIntro,
        })
          .then((res) => {
            this.$message({
              showClose: true,
              message: "添加" + res.data.msg,
              type: res.data.code === 0 ? "success" : "error",
            });
            this.$emit("refresh", {});
            this.closeMask();
          })
          .catch((res) => {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error",
            });
          });
      } else {
        // 弹出错误框
        this.$message({
          showClose: true,
          message: "请填写必要参数",
          type: "error",
        });
      }
    },

    // 修改
    resetInfo() {
      if (this.checkInfo()) {
        updateHospital({
          id: this.infos.id,
          hospitalName: this.form.hospitalName,
          province: this.form.province_id,
          locationDes: this.form.locationDes,
          hospitalIcon: this.img_main,
          locationLng: this.form.locationLng,
          locationLat: this.form.locationLat,
          showImage: this.img_arr,
          hospitalIntro: this.form.hospitalIntro,
        })
          .then((res) => {
            if (res.data.code === 0) {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.$emit("refresh", {});
            } else {
              this.$message.error(res.data.msg);
            }
            this.closeMask();
          })
          .catch((res) => {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error",
            });
          });
      } else {
        // 弹出错误框
        this.$message({
          showClose: true,
          message: "请填写必要参数",
          type: "error",
        });
      }
    },

    // 检测参数是否都填写完毕
    checkInfo() {
      if (!this.img_main) {
        this.img_main = this.form.hospitalIcon;
      }
      if (!this.img_arr) {
        this.img_arr = this.form.showImage;
      }
      return !(
        !this.form.hospitalName ||
        !this.form.province_id ||
        !this.form.locationDes ||
        !this.form.locationLng ||
        !this.form.locationLat ||
        !this.form.hospitalIntro
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  padding-right: 1%;
  height: 470px;
  max-height: 480px;
  overflow: auto;
  box-sizing: border-box;
}
.form {
  width: 400px;
  margin-right: 16px;
  margin-bottom: 10px;
}
.img-list {
  display: inline-block;
  vertical-align: middle;
  .img-item {
    width: 150px;
    height: 150px;
    border: 1px solid #ccc;
    display: inline-block;
    vertical-align: middle;
    overflow: hidden;
    margin-right: 10px;
    position: relative;
    .img {
      width: 100%;
    }
    .del-btn {
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.3);
      color: #fff;
      line-height: 150px;
      text-align: center;
      font-size: 40px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      cursor: pointer;
      display: none;
    }
    &:hover {
      .del-btn {
        display: block;
      }
    }
  }
}

.form-control {
  width: 100%;
  padding-right: 6px;
  min-height: 300px;
  -webkit-overflow-scrolling: touch;
  resize: none;
  outline: 0 none;
  margin-top: 12px;
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: rgba(13, 20, 30, 1);
  line-height: 19px;
  opacity: 0.6;
}
</style>
